//
//  Ch2_2ViewController.swift
//  learn-gl-es-swift
//
//  Created by LimitLiu on 2019/7/2.
//  Copyright © 2019 LimitLiu. All rights reserved.
//

import UIKit
import OpenGLES.ES2

let kGLDefaultFramesPerSecond = 30

class GLController: UIViewController {

    var displayLink: CADisplayLink!
    var isPaused: Bool {
        get {
            return displayLink.isPaused
        }
        set {
            displayLink.isPaused = newValue
        }
    }
    var preferredFramesPerSecond: Int {
        set {
            displayLink.preferredFramesPerSecond = newValue
        }
        get {
            return displayLink.preferredFramesPerSecond
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let v = GLView(frame: view.bounds, context: EAGLContext(api: .openGLES2)!)
        self.view = v
        if let view = self.view as? GLView {
            view.isOpaque = true
            view.delegate = self
        }
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        displayLink = CADisplayLink(target: self, selector: #selector(drawRect(_:)))
        displayLink.add(to: RunLoop.current, forMode: .default)
        preferredFramesPerSecond = kGLDefaultFramesPerSecond
    }
    
    @objc func drawRect(_ rect: CGRect) {
        if let view = self.view as? GLView {
            view.display()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone
                ? .portraitUpsideDown : .allButUpsideDown
        }
    }
    
}

extension GLController: GLViewDelegate {
    func glkView(_ view: GLView, drawIn rect: CGRect) {
    }
}

